package cn.virens.web.components.beetl.format;

import org.beetl.core.Format;

public class ImageFormat implements Format {
	public static final String DEF_AVATAR = "/assets/img/avatar.png";
	public static final String DEF_IAMGE = "/assets/img/default.png";
	public static final String IAMGE_PATH = "";

	@Override
	public Object format(Object data, String pattern) {
		if ("avatar".equals(pattern)) {
			return format(data, "/down/thumb/", DEF_AVATAR);
		} else if ("src".equals(pattern)) {
			return format(data, "/down/image/", DEF_IAMGE);
		} else {
			return format(data, "/down/thumb/", DEF_IAMGE);
		}
	}

	private static String format(Object data, String prefix, String def) {
		if (data != null && startWithHttp(data)) {
			return String.valueOf(data);
		} else if (data != null && !"".equals(data)) {
			return IAMGE_PATH + prefix + data;
		} else {
			return def;
		}
	}

	private static boolean startWithHttp(Object obj) {
		String src = String.valueOf(obj);

		// 先将str转为字符数组
		char[] cs = src.toCharArray();
		if (cs.length < 7) { return false; }

		// 验证字符数组开头4位
		if (cs[0] != 'h' && cs[0] != 'H') { return false; }
		if (cs[1] != 't' && cs[1] != 'T') { return false; }
		if (cs[2] != 't' && cs[2] != 'T') { return false; }
		if (cs[3] != 'p' && cs[3] != 'P') { return false; }

		// 判断是不是https协议
		if ((cs[4] == 's' || cs[4] == 'S') && cs.length > 8) {
			if (cs[5] != ':') { return false; }
			if (cs[6] != '/') { return false; }
			if (cs[7] != '/') { return false; }

			return true;
		}

		// 判断http协议
		if (cs[4] != ':') { return false; }
		if (cs[5] != '/') { return false; }
		if (cs[6] != '/') { return false; }

		return true;
	}
}
